﻿namespace MvcXRepairAdmin.Repository.SQL
{
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using XRepair.Models;
    using RepositoryUtil.SQL;

    public class AccountDAO : BaseDAO
    {
        public IEnumerable<User> GetAllUsers()
        {
            return null;
        }

        public bool AddNewUser(User user)
        {
            return false;
        }

        public bool DeactivateUser(int userId)
        {
            return false;
        }

        public bool ReactivateUser(int userId)
        {
            return false;
        }

        public User GetUserInfoByCredentials(string username, string password)
        {
            string spName = "GetUserInfoByUserName";

            DataTable resultTab = null;
            User user = null;

            using (var conn = XRepairConn)
            {
                conn.Open();

                SqlCommand command = new SqlCommand(spName, conn);
                command.CommandType = CommandType.StoredProcedure;

                command.AddInParameter("Username", username);
                command.AddInParameter("Password", password);

                resultTab = command.ExecuteDataTable();
            }

            if (resultTab != null && resultTab.Rows.Count > 0)
            {
                user = this.ConvertDataTableToUserModel(resultTab);
            }

            return user;
        }

        private User ConvertDataTableToUserModel(DataTable data)
        {
            User user = null;

            if (data != null && data.Rows.Count == 1)
            {
                user = new User();
                DataRow infoRow = data.Rows[0];

                user.ID = SqlUtil<int>.GetValue(infoRow, "ID");
                user.Password = SqlUtil<string>.GetValue(infoRow, "Password");
                user.RoleID = SqlUtil<int>.GetValue(infoRow, "RoleID");
                user.Salt = SqlUtil<string>.GetValue(infoRow, "Salt");
                user.Username = SqlUtil<string>.GetValue(infoRow, "Username");
                user.Alias = SqlUtil<string>.GetValue(infoRow, "Alias");
            }

            return user;
        }
    }
}
